// npm 包
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import ProForm, { ModalForm } from '@ant-design/pro-form';
import { Button, Form, AutoComplete, message, Switch, Table } from 'antd';
// import { selectStudent, getStudentSearchOptions } from '@/global/service';
import { v4 as uuidv4 } from 'uuid';

// 数据请求
import { getListByAId, copyPaper} from '../service';
import { getActivityListByName } from '../service';
import { number } from 'echarts';

interface SelectFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onReload: () => void;
  selectList: any;
  id:number;
}

const TableList: React.FC<SelectFormProps> = (props) => {
  const actionRef = useRef<ActionType>();
  const { modalVisible, onCancel, onReload, id } = props;
  const [data, setData] = useState();
  const [selectedArr, setSeletedArr] = useState([]);
  const [switchArr, setSwitchArr] = useState([]);
  const [form] = Form.useForm();
  const [options, setOptions] = useState([]);
  const [activityId, setActivityId] = useState(0);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>();
  const [switchId, setSwitchId] = useState();
  // useEffect(() => {
  //   if (selectedArr) {
  //     // setEditableRowKeys(() => {
  //     //   return options.map((item) => item.id);
  //     // });
  //     selectedArr.some((item) => {
  //       if (item.copyQuiz === true) {
  //         setSwitchId(item.id);
  //         return;
  //       }
  //     });
  //   }
  // }, [selectedArr]);
  // useEffect(() => {
  //   let _recordList = data;
  //   if (switchId) {
  //     _recordList = data.map((item) => {
  //       if (item.id === switchId) {
  //         item.copyQuiz = true;
  //       } else {
  //         item.copyQuiz = false;
  //       }
  //       return item;
  //     });
  //   }
  //   console.log(_recordList);
  //   setSeletedArr(_recordList);
  //   // setData(_recordList);
  // }, [switchId]);
  useEffect(() => {
    fetchData()
  }, [activityId]);
  const fetchData = async () => {
    const msg = await getListByAId({ productId:activityId });
            msg.result.forEach((val, idx) => {
              val.copyQuiz = true
              // val.disabled = true
              })
            setData(msg.result);
  };
  const onSearch = async (key: string) => {
    console.log(key);
    try {
      const data = await getActivityListByName({name:key});
      const optionList = !key
        ? []
        : data.result.map((item: { id: any; name: any;}) => ({
            // id: item.id,
            label: `${item.id}-${item.name}`,
            value: `${item.id}-${item.name}`,
            key: `${item.id}`,
          }));
          console.log(optionList)
      setOptions(optionList);
    } catch (error) {
      message.error('搜索失败');
    }
  };
  const onSelect = (data: any, option: any) => {
    console.log(data);
    console.log(option);
    // setActivityId(0);
    setActivityId(option.key);
    // actionRef.current?.reload();
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };
  
  const handleSwitchChange = (id:number,checked:boolean) => {
    let arr = switchArr
    if(arr.length > 0 ){
      
      for(let item of arr){
        if(id == item.id){
          item.copyQuiz = checked
        }
        else{
          let json = {id:0,copyQuiz:true}
          json.id = id
          json.copyQuiz = checked
          arr.push(json)
        }
      }
    }else{
      let json = {id:0,copyQuiz:true}
          json.id = id
          json.copyQuiz = checked
          arr.push(json)
    }
    setSwitchArr(arr)
  };
  const columns = [
    
    {
      title: '试卷ID',
      dataIndex: 'id',
      width:'80px',
      // hideInForm: true,
    },
    {
      title: '试卷名称',
      dataIndex: 'name',
    },
    {
      title: '创建人',
      dataIndex: 'itemName',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      width:'200px',
      ellipsis: true,
    },
    {
      title: '难度',
      dataIndex: 'level',
      valueEnum: {
        'high': '较高',
          'common': '普通',
          'low': '较低',
          'simple': '简单',
      },
    },
    {
      title: '完成奖励',
      dataIndex: 'complateAward',
    },
    {
      title: '及格奖励',
      dataIndex: 'passAward',
    },
    {
      title: '满分奖励',
      dataIndex: 'fullAward',
    },
    // ProTable.SELECTION_COLUMN,
    {
      title: '复制试题',
      dataIndex: 'copy',
      render: (_, record: any) => (
        <Switch
          onChange={(checked: boolean) => {
            handleSwitchChange(record.id,checked);
          }}
          // disabled = {record.disabled}
          defaultChecked = {record.copyQuiz}
          // onChange={(checked) => {
          //   if (checked === true) {
          //     setSwitchId(record.id);
          //   } else {
          //     setSwitchId();
          //   }
          // }}
          // checked={record.id === switchId ? true : false}
        />
      ),
    },
  ];
  const onFinish = async () => {
    let copyList = [];
    // console.log(switchArr);
    // console.log(selectedArr);
    let switchArrData = switchArr
    let selectedArrData = selectedArr
    for(let item of selectedArrData){
      for(let item1 of switchArrData){
          if(item1.id == item.id)
          item.copyQuiz = item1.copyQuiz
      }
    }
    // console.log(selectedArrData);
    for(let n of selectedArrData){
      let json = {}
      json.paperId = n.id
      json.copyQuiz = n.copyQuiz
      copyList.push(json)
    }
    console.log(copyList);
    // return
    const res = await copyPaper({ activityId: id, copyObjectList:copyList});
    console.log(res);

    if (res.code == 200) {
      form.resetFields();
      // setActivityId(0);
      onCancel();
      onReload();
    }
    // selectedArr.forEach((val1, idx1) => {
    //   data.forEach((val2, idx2) => {
    //     if (val2.id == val1) {
    //       selectedItemDetailArr.push(val2);
    //     }
    //   });
    // });
    // callback(selectedItemDetailArr);
    // onCancel();
  };

 

  return (
    <ModalForm
      title="复制试卷"
      visible={modalVisible}
      width="60%"
      modalProps={{
        onCancel: (val: any) => {
          form.resetFields();
          setActivityId(0);
          onCancel();
        },
        bodyStyle: {
          maxHeight: '550px',
          overflow: 'auto',
        },
        maskClosable:false
      }}
      form={form}
      submitter={{
        render: (props, doms) => {
          return [
            <Button
              type="ghost"
              onClick={() => {
                form.resetFields();
                setActivityId(0);
                onCancel();
              }}
              key={uuidv4()}
            >
              取消
            </Button>,
            <Button
              type="primary"
              disabled={selectedArr.length > 0 ? false : true}
              onClick={() => onFinish()}
              key={uuidv4()}
            >
              确定
            </Button>,
          ];
        },
      }}
    >
      <ProForm.Item
        label="课程名称"
        name="_uid"
        rules={[
          {
            required: true,
            message: '请选择课程名称',
          },
        ]}
      >
        <AutoComplete
          options={options}
          onSelect={onSelect}
          onSearch={onSearch}
          placeholder="请选择课程名称"
        />
      </ProForm.Item>
      {activityId > 0 && (
      //   <Table
      //   columns={columns}
      //   dataSource={data}
      //   rowSelection={{
      //     type: 'checkbox',
      //     ...rowSelection,
      //   }}
        
      // />
      <ProTable<{}>
          actionRef={actionRef}
          rowKey="id"
          dataSource={data}
          columns={columns}
          pagination={false}
          rowSelection={{
            onChange: (val: any,row: any) => {
              // for(let item of data){

              // }
              setSeletedArr(row);
            },
          }}
          search={false}
          toolBarRender={false}
        />
      )}
    </ModalForm>
  );
};

export default TableList;
